package com.example.demo.utils;

import com.example.demo.Task.hbutetc.Login;
import com.example.demo.domain.result.StudentInfo;
import com.example.demo.exception.ParamErrorException;
import com.example.demo.exception.PasswordErrorException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 湖北工业大学工程技术学院登陆工具类
 * @author lizijian
 */
@Slf4j
public class HbutEtcLoginUtil {
    private static final String ETC_ALL_PASS_GRADE = "http://202.114.190.75/student/integratedQuery/scoreQuery/allPassingScores/callback";
    public static CloseableHttpClient login(String username, String password)
        throws  PasswordErrorException {
        long begin = System.nanoTime();
        password = DigestUtils.md5Hex(password + "{Urp602019}");
        Login loginThread = new Login(username, password);
        System.out.println("loginThread:" + loginThread);
        for (int i = 0; i < 7; i++) {
            new Thread(loginThread).start();
        }
        try {
            synchronized (loginThread) {
                loginThread.wait(7000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.nanoTime();
        long time = end - begin;
        log.info("login_time:" + TimeUnit.NANOSECONDS.toMillis(time));
        CloseableHttpClient httpClient = loginThread.getHttpClient();
        if(httpClient==null){
            throw new PasswordErrorException();
        }
        return httpClient;
    }
    /**
     * 获取学生信息
     * @param username 用户名
     * @param password 密码
     * @return 学生信息类
     * @throws IOException
     */
    public static StudentInfo getStudentInfo(String username, String password)
        throws IOException, PasswordErrorException {
        String url = "http://202.114.190.75/student/rollManagement/rollInfo/index";
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
        CloseableHttpClient httpClient = login(username, password);
        CloseableHttpResponse execute = httpClient.execute(httpPost);
        String s = EntityUtils.toString(execute.getEntity(), "utf-8");
        Document parse = Jsoup.parse(s);
        log.info(parse.html());
        log.info("title:"+parse.title());
        Elements largest = parse.getElementsByClass("self profile-user-info profile-user-info-striped setLabelWidth");
        StudentInfo studentInfo = new StudentInfo();
        for (Element element : largest) {
            Elements row = element.getElementsByClass("profile-info-row");
            for (Element info : row) {
                Elements names = info.getElementsByClass("profile-info-name");
                Elements values = info.getElementsByClass("profile-info-value");
                for (int i=0;i< names.size();i++){
                    String name = names.get(i).html();
                    String value = values.get(i).html();
                    if("班级".equals(name)){
                        studentInfo.setStudentClass(value);
                    }else if("学号".equals(name)){
                        studentInfo.setStudentId(value);
                    }else if("姓名".equals(name)){
                        studentInfo.setName(value);
                    }else if("性别".equals(name)){
                        studentInfo.setSex(value);
                    }else if("民族".equals(name)){
                        studentInfo.setNation(value);
                    }else if("院系".equals(name)){
                        studentInfo.setCollege(value);
                    }else if("专业".equals(name)){
                        studentInfo.setMajor(value);
                    }
                }
            }
        }
        return studentInfo;
    }

    public static String getEtcGradeResult(String username, String password) throws PasswordErrorException, IOException {
        CloseableHttpClient httpClient = HbutEtcLoginUtil.login(username, password);
        HttpGet httpGet = new HttpGet(ETC_ALL_PASS_GRADE);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(300 * 1000)
                .setConnectTimeout(10 * 1000).build();
        httpGet.setConfig(requestConfig);
        httpGet.setHeader("Content-Type", "application/json;charset=utf-8");
        HttpResponse response = null;
        String result = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "utf-8");
            httpClient.close();
        } catch (IOException e) {
            throw new IOException();
        }
        return result;
    }

    public static void main(String[] args) throws IOException, PasswordErrorException {
        StudentInfo studentInfo = getStudentInfo("20201017116", "Tang1234");
        System.out.println(studentInfo);
    }
}
